<?php

namespace app\api\controller;

use addons\vip\library\Service;
use app\admin\model\Bookclass;
use app\admin\model\Books;
use app\admin\model\books\BookShelf;
use app\admin\model\books\Browse;
use app\admin\model\vip\Viprecore;
use app\common\controller\Api;
use Monolog\Handler\BrowserConsoleHandler;
use addons\vip\model\Record;
use addons\vip\model\Vip as VipModel;
use think\Db;

/**
 * 会员接口
 */
class Money extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取会员价格列表
     * @ApiMethod (GET)
     **/
    public function vipList(){
        $list = (new \app\admin\model\Vip())->where('status','normal')->order('level desc')->select();
        $this->success('请求成功',$list);
    }

    /**
     * 购买会员
     * @ApiMethod (POst)
     * @param int vip_id vip_id
     * @param int token token
     * @param int appid appid
     * @param int paytype 支付方式 alipay,wechat
     */
    public function submit(){
        $vip_id = $this->request->post('vip_id');
        $token = $this->request->post('token');
        $appid = $this->request->post('appid');
        $paytype = $this->request->post('paytype');
        $uid = $this->getToken($token);
        $userInfo = (new \app\admin\model\User())->find($uid);

        $vipInfo = (new VipModel())->where('id',$vip_id)->find();
        if (!$vipInfo) {
            $this->error('未找到VIP相关信息');
        }

        $userVip = (new Viprecore())->where(['user_id'=>$uid,'status'=>'active'])->find();

        if ($userVip && $userVip['level'] > $vipInfo['level']) {
            $this->error('当前VIP等级已高于购买的VIP等级');
        }
        if (!in_array($paytype, ['alipay', 'wechat'])) {
            $this->error('支付方式错误');
        }

        $amount = $vipInfo->getPriceByDays($vipInfo['days']);
        $insert = [
            'user_id' => $uid,
            'vip_id'  => $vip_id,
            'level'   => $vipInfo->level,
            'days'    => $vipInfo->days,
            'amount'  => $vipInfo->price,
            'status'  => 'created',
        ];
        $vipRecord = Record::create($insert, true);
        $notifyurl = $this->request->root(true) . '/addons/epay/api/Vipnotifyx/type/' . $paytype;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $paytype ;
        $method = '';
        try {
            $response = \addons\vip\library\Order::submit($vipInfo->id, $vipRecord->id, $amount, $paytype, 'app', '', $notifyurl, $returnurl);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success(__(''), $response);
    }






}
